package com.richper.springcloudh2020.controller;

import com.richper.springcloudh2020.entities.CommonResult;
import com.richper.springcloudh2020.entities.Payment;
import com.richper.springcloudh2020.lb.LoadBalance;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import java.net.URI;
import java.util.List;

@Controller
@RequestMapping(value = "/consumer")
@Slf4j
public class OrderController {
    @Resource
    private RestTemplate restTemplate;
    @Resource
    private LoadBalance loadBalance;
    @Resource
    private DiscoveryClient discoveryClient;
//    private static final String PAYMENT_URL = "http://127.0.0.1:8001/";
    private static final String PAYMENT_URL = "http://CLOUD-PAYMENT-SERVICE/";

    @GetMapping(value = "/payment/insertPayMent")
    @ResponseBody
    public CommonResult<Payment> insertPayMent(Payment payment){
        return restTemplate.postForObject(PAYMENT_URL+"payment/insertPayMent",payment,CommonResult.class);
    }

    @GetMapping(value = "/payment/queryPayMentByID/{id}")
    @ResponseBody
    public CommonResult<Payment> queryPayMentByID(@PathVariable Long id){
        return restTemplate.getForObject(PAYMENT_URL+"payment/queryPayMentByID/"+id,CommonResult.class);
    }
    @GetMapping(value = "/payment/discovery")
    @ResponseBody
    public CommonResult<Payment> discovery(){
        return restTemplate.getForObject(PAYMENT_URL+"payment/discovery",CommonResult.class);
    }

    @GetMapping(value = "/payment/queryPayMentByID/entity/{id}")
    @ResponseBody
    public CommonResult queryPayMentEntityByID(@PathVariable Long id){
        ResponseEntity<CommonResult> forEntity = restTemplate.getForEntity(PAYMENT_URL + "payment/queryPayMentByID/" + id, CommonResult.class);
        HttpStatus statusCode = forEntity.getStatusCode();
        log.info(forEntity.getHeaders().toString());
        if(statusCode.is2xxSuccessful()){
            return forEntity.getBody();
        }else {
            return new CommonResult<>(444,"查询失败");
        }
    }

    @GetMapping("/payment/MyLB")
    @ResponseBody
    public String MyLB(){
        List<ServiceInstance> instances = discoveryClient.getInstances("CLOUD-PAYMENT-SERVICE");
        if (instances.size() <= 0) {
            return null;
        }
        URI uri = loadBalance.instance(instances).getUri();
        return restTemplate.getForObject(uri+"/payment/lb/getPort", String.class);
    }
}